const express = require('express');
const _ = require('underscore');
const jsonfile = require('jsonfile');
const path = require('path');
const config = require('config');
const moment = require('moment');
const crypto = require('crypto');
const IMMessage = require('../mongo/im-message');
const co = require('co');
var rongCloud = require('rongcloud-sdk');
const logger = require('flogger').getLogger();

const Utility = require('../util/util').Utility;
const Session = require('../util/session');

const router = express.Router();

rongCloud.init(config.RONGCLOUD_APP_KEY, config.RONGCLOUD_APP_SECRET);

const User = require('../models').User;
const OnlineStatus = require('../models').OnlineStatus;

router.post('/message_receive', validateRongCloudSignature, function (req, res, next) {
  co(function*() {
    let msg = req.body;
    let content = msg.content;
    try {
      content = JSON.parse(content);
    } catch (e) {
      logger.warn('content 不能解析成json');
    }
    msg.content = content;
    msg.timestamp = parseInt(msg.timestamp);
    msg.msgTimestamp = parseInt(msg.msgTimestamp);
    let immsg = new IMMessage(msg);

    yield immsg.save();
    res.status(200).end('');
    logger.info('消息保存成功');
  }).catch(next);
});

router.post('/online_status_changed', validateRongCloudSignature, function (req, res, next) {
  co(function*() {
    let statusList = req.body;
    for (let status of statusList) {
      yield OnlineStatus.upsert({
        userId: Utility.stringToNumber(status.userid),
        status: parseInt(status.status),
        os: status.os,
        timestamp: parseInt(status.time)
      });
    }
    res.status(200).end('');
  }).catch(next);
});

/**
 * @api {get} /webim/misc/oss_signature 获取OSS签名信息
 * @apiDescription  Web端上传文件参考<a href="https://help.aliyun.com/document_detail/31927.html">Web端直传实践</a>
 *
 * @apiName GetOssSignature
 * @apiGroup Misc
 * @apiVersion 0.1.0
 *
 * @apiSuccessExample 成功响应:
 *    HTTP/1.1 200 OK
 *    {
 *      "accessKeyId": "MLaPoaRe9VOUqQgh",
 *      "url": "http://impic.oss-cn-shenzhen.aliyuncs.com",
 *      "policy": "eyJleHBpcmF0aW9uIjoiMjAxNi0wOS0yMlQwMzowMjowMS40ODBaIiwiY29uZGl0aW9ucyI6W3siYnVja2V0IjoiaW1waWMifSxbImNvbnRlbnQtbGVuZ3RoLXJhbmdlIiwwLDEwNDg1NzYwXSxbInN0YXJ0cy13aXRoIiwiJGtleSIsInRlc3QvMjAxNjA5L2VwdGpiLyJdXX0=",
 *      "signature": "soj2pQOIRNcO6QtHY2UqWWsm3AY=",
 *      "dir": "test/201609/eptjb/",
 *      "expires": 1474513321480
 *    }
 */

router.get('/oss_signature', function (req, res, next) {
  co(function*() {
    let userId = Session.getCurrentUserId(req);
    let userUid = yield Session.getCurrentUserUid(userId, User);
    let timeDir = moment().format('YYYYMM');
    // 时间/用户/图片
    let uploadDir = path.join(config.OSS_UPLOAD_ROOT, timeDir, userUid, '/');
    // Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了, 有效时间1小时
    let expires = moment().add('60', 'minutes');

    var policyText = {
      expiration: expires.toISOString(),
      conditions: [
        {bucket: config.OSS_IMAGE_BUCKET},
        ['content-length-range', 0, config.OSS_LIMIT_SIZE],
        ['starts-with', '$key', uploadDir]
      ]
    };

    var policyBase64 = new Buffer(JSON.stringify(policyText)).toString('base64');
    let signature = crypto.createHmac('sha1', config.OSS_ACCESS_SECRET);
    signature = signature.update(new Buffer(policyBase64, 'utf8')).digest('base64');

    res.status(200).json({
      accessKeyId: config.OSS_ACCESS_KEY_ID,
      url: config.OSS_URL,
      policy: policyBase64,
      signature: signature,
      dir: uploadDir,
      expires: expires.valueOf()
    });
  }).catch(next);

});

function validateRongCloudSignature(req, res, next) {
  logger.info('收到新消息', req.body);

  let timestamp = req.query.timestamp;
  let nonce = req.query.nonce;
  let signature = req.query.signature;

  // appKey不一致
  let appKey = req.query.appKey;
  if (appKey !== config.RONGCLOUD_APP_KEY) {
    logger.info('appKey 不正确');
    return res.status(403).end('');
  }

  if (rongCloud.validateSignature(timestamp, nonce, signature)) {
    logger.info('签名不正确');
    return res.status(403).end('');
  }
  next();
}

module.exports = router;
